import router from '@/router'
import store from '@/store'
import axios from 'axios'

export const baseURL = 'http://pcapi-xiaotuxian-front-devtest.itheima.net/'

const createAxios = axios.create({ baseURL, timeout: 5000 })

// 请求拦截器
createAxios.interceptors.request.use(
  (config) => {
    const { prefile = {} } = store.state.user
    if (prefile && prefile.token) {
      config.headers.Authorization = `Bearer ${prefile.token}`
    }
    return config
  },
  (error) => Promise.reject(error)
)

// 响应拦截器
createAxios.interceptors.response.use(
  (response) => response.data,
  (error) => {
    if (error.response && error.response.status === 401) {
      store.commit('user/setUser', {}) // 清除缓存信息
      const fullPath = encodeURIComponent(router.currentRoute.value.fullPath)
      router.push(`/login?redirectUrl=${fullPath}`)
    }
    return Promise.reject(error)
  }
)

export default (url, data, method = 'GET') => {
  const params = method.toLocaleUpperCase() === 'GET' ? 'params' : 'data'
  return createAxios({
    url,
    [params]: data,
    method
  })
}
